wifi.setmode(1)
wifi.sta.config("TP-LINK_S00", "shuang00")

led1 = 0
-- led2 = 4

doorled = 1

gpio.mode(led1, gpio.OUTPUT)
gpio.write(led1, gpio.HIGH)
-- gpio.mode(led2, gpio.OUTPUT)
-- gpio.write(led2,gpio.LOW)

gpio.mode(doorled, gpio.OUTPUT)
gpio.write(doorled, gpio.HIGH)

tmr.alarm(1, 1000, 1, function()
    if (wifi.sta.getip() ~= nil) then
        tmr.stop(1)
        print("Config done, IP is " .. wifi.sta.getip())

        m = mqtt.Client("esp8266_doorled", 120, "m_1/esp8266_1", "kJPUTRCw3Wz1P2PntO+1Dvkn2Q8279RtsdfpJB022+w=")
        -- m:lwt("/lwt", "offline", 0, 0)
        m:on("connect", function(client) print("connect") end)
        m:on("offline", function(client) print("offline") end)
        m:on("message", function(client, topic, data)
            if data == "esp8266_myhome_doorled_on" then
                gpio.write(led1, gpio.LOW);
                gpio.write(doorled, gpio.LOW);
                -- tmr.unregister(2)
                c = tmr.alarm(2, 60000, 0, function()
                    gpio.write(led1, gpio.HIGH);
                    gpio.write(doorled, gpio.HIGH);
                    collectgarbage();
                end )
                m:publish("esp8266", "esp8266_myhome_doorled_60s " .. tostring(c), 0, 0, function(client) print("sent esp8266_myhome_doorled_60s " .. tostring(c)) end)
                m:publish("esp8266", "esp8266_myhome_doorled_on_ok", 0, 0, function(client) print("sent esp8266_myhome_doorled_on_ok") end)

            elseif data == "esp8266_myhome_doorled_off" then
                gpio.write(led1, gpio.HIGH);
                gpio.write(doorled, gpio.HIGH);
                m:publish("esp8266", "esp8266_myhome_doorled_off_ok", 0, 0, function(client) print("sent esp8266_myhome_doorled_off_ok") end)

            elseif data == "esp8266_myhome_doorled_heartbeat" then
                -- if get beat ,reset restart timer
                tmr.unregister(4)
                tmr.alarm(4, 600000, 1, function()
                    node.restart()
                end )

            end
        end )

        -- for TLS: m:connect("192.168.11.118", secure-port, 1)
        m:connect("m_1.mqtt.iot.gz.baidubce.com", 1883, 0, 1,function(client)
            print("connected")
            m:subscribe("esp8266", 1, function(client) print("subscribe success") end)
            tmr.alarm(4, 600000, 1, function()
                    node.restart()
                end )
        end ,
        function(client, reason)
            print("connect error:"..reason)
            tmr.alarm(3, 30000, 1, function()
                node.restart()
            end )
        end )

        -- per 5 min send a beat
        tmr.alarm(5, 300000, 1, function()
            m:publish("esp8266", "esp8266_myhome_doorled_heartbeat", 0, 0, function(client) print("sent esp8266_myhome_doorled_heartbeat") end)
        end )

    end

end )

-- endregion
